package com.torry.edss.integration.dingtalk;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.torry.edss.domain.accessor.CompanyAccessor;
import com.torry.edss.domain.accessor.LimitUpAccessor;
import com.torry.edss.domain.model.Company;
import com.torry.edss.domain.model.LimitUp;
import com.torry.edss.infras.entity.LimitUpDO;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class DingTalkClient {
    final String CUSTOM_ROBOT_TOKEN = "1c17eeb21135fd7488cf9db9f7965de7301023f7d4a97997b255bfc945d77315";
    final String SECRET = "SEC4d1efff9aa9ba5ad3cda4c949ef2cd25dbce3766367d901092247e4cd94eefd4";

    final String USER_ID_TORRY = "010801276560945008";
    final String USER_ID_TD = "2903020823939323";

    final String CUSTOM_ROBOT_TOKEN_TEST = "fd40e2b00fb2897b2cdafbc5063a93e4d3c9a4e7a48e9528565c51bc1971ed84";
    final String SECRET_TEST = "SECab107a2705db9e9168d02dfdc1a0f50ae7e3c71b8057e0cca3d2521b484b59a9";
    @Resource
    private CompanyAccessor companyAccessor;
    @Resource
    private LimitUpAccessor limitUpAccessor;

    public void sendMsg(Set<Long> list, Map<Long, BigDecimal> guardMap, Map<Long, String> intervalMap) {
        List<String> codes = new ArrayList<>();
        List<String> names = new ArrayList<>();
        List<String> details
                = list.stream().map(companyId -> {
            Company company = companyAccessor.getById(companyId);
            codes.add(company.getCode());
            names.add(company.getName());
            LimitUp limitUp = limitUpAccessor.list(new LambdaQueryWrapper<LimitUpDO>().eq(LimitUpDO::getCompanyId, companyId).orderByDesc(LimitUpDO::getDate)).get(0);
            String logic = "-";
            if (limitUp != null && StringUtils.isNotBlank(limitUp.getLogic())) {
                logic = limitUp.getLogic();
            }
            return company.getCode() + company.getName() + " 收盘: " + intervalMap.get(companyId) + " 止损位: " + guardMap.get(companyId);
        }).collect(Collectors.toList());


        try {
            Long timestamp = System.currentTimeMillis();
            System.out.println(timestamp);

            String stringToSign = timestamp + "\n" + SECRET;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SECRET.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            System.out.println(sign);

            //sign字段和timestamp字段必须拼接到请求URL上，否则会出现 310000 的错误信息
            com.dingtalk.api.DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?sign=" + sign + "&timestamp=" + timestamp);
            OapiRobotSendRequest req = new OapiRobotSendRequest();
            /**
             * 发送文本消息
             */
            //定义文本内容
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            StringBuilder contentBuilder = new StringBuilder();
            contentBuilder.append("【涨停十字星】左侧股池，尾盘关注： \n  ");
            contentBuilder.append(String.join("\n  ", details));
            contentBuilder.append("\n");
            contentBuilder.append("代码复制:\n  ");
            contentBuilder.append(String.join(",", codes));
            contentBuilder.append("\n");
            contentBuilder.append("名称复制:\n  ");
            contentBuilder.append(String.join(",", names));
            contentBuilder.append("\n");

            text.setContent(contentBuilder.toString());
            //定义 @ 对象
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//            at.setIsAtAll(true);
            at.setAtUserIds(Arrays.asList(USER_ID_TD, USER_ID_TORRY));
            //设置消息类型
            req.setMsgtype("text");
            req.setText(text);
            req.setAt(at);
            OapiRobotSendResponse rsp = client.execute(req, CUSTOM_ROBOT_TOKEN);
            System.out.println(rsp.getBody());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public void sendMsg(Set<Long> list) {
        List<String> codes = new ArrayList<>();
        List<String> names = new ArrayList<>();
        List<String> details
                = list.stream().map(companyId -> {
            Company company = companyAccessor.getById(companyId);
            codes.add(company.getCode());
            names.add(company.getName());
            return company.getCode() + " " + company.getName();
        }).collect(Collectors.toList());

        try {
            Long timestamp = System.currentTimeMillis();
            System.out.println(timestamp);

            String stringToSign = timestamp + "\n" + SECRET_TEST;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SECRET_TEST.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            System.out.println(sign);

            //sign字段和timestamp字段必须拼接到请求URL上，否则会出现 310000 的错误信息
            com.dingtalk.api.DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?sign=" + sign + "&timestamp=" + timestamp);
            OapiRobotSendRequest req = new OapiRobotSendRequest();
            /**
             * 发送文本消息
             */
            //定义文本内容
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            StringBuilder contentBuilder = new StringBuilder();
            contentBuilder.append("【暴力洗盘】，跳空低开关注： \n  ");
            contentBuilder.append(String.join("\n  ", details));
            contentBuilder.append("\n");
            contentBuilder.append("代码复制:\n  ");
            contentBuilder.append(String.join(",", codes));
            contentBuilder.append("\n");
            contentBuilder.append("名称复制:\n  ");
            contentBuilder.append(String.join(",", names));
            contentBuilder.append("\n");

            text.setContent(contentBuilder.toString());
            //定义 @ 对象
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//            at.setIsAtAll(true);
            at.setAtUserIds(Arrays.asList(USER_ID_TORRY));
            //设置消息类型
            req.setMsgtype("text");
            req.setText(text);
            req.setAt(at);
            OapiRobotSendResponse rsp = client.execute(req, CUSTOM_ROBOT_TOKEN_TEST);
            System.out.println(rsp.getBody());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
